import os
import sys
import shutil 
from jsbeautifier import beautify_file,default_options as js_beautify_default_options

def createPathIfNotExist(dirName):
	if not os.path.exists(dirName):
		os.makedirs(dirName)

def format(fileName,output="."):
	formatName = output + "\\" + os.path.basename(fileName.replace(".js",".format.js"))
	js_options = js_beautify_default_options()
	print "format... " + formatName
	formatContent = beautify_file(fileName, js_options)
	formatFile = open(formatName,"w");
	formatFile.write(formatContent)
	formatFile.close()
	return formatName

def link(fileName,lib="..\\..\\closure-library",output="."):
	linkedFileName = output + "\\" + os.path.basename(fileName.replace(".js",".linked.js"))
	cmd = lib + "\\closure\\bin\\calcdeps.py"
	cmd += " -i " + fileName
	cmd += " -p " + lib + " -o script"
	#cmd += " -c " + lib + "\\compiler.jar"
	#cmd += ' -f "--compilation_level=ADVANCED_OPTIMIZATIONS"'
	cmd += ' > ' + linkedFileName
	print 'link... ' + linkedFileName
	os.popen(cmd).read()
	return linkedFileName;

def compileIt(fileName,lib="..\\..\\closure-library",output=".",compiler=None):
	if not compiler :
		compiler = lib + "\\..\\compiler.jar"
	compiledFileName = output + "\\" + os.path.basename(fileName.replace(".js",".compiled.js"))
	cmd = lib + "\\closure\\bin\\calcdeps.py"
	cmd += " -i " + fileName
	cmd += " -p " + lib + " -o compiled"
	cmd += " -c " + compiler
	cmd += ' -f "--compilation_level=ADVANCED_OPTIMIZATIONS"'
	cmd += ' > ' + compiledFileName
	print 'compile... ' + compiledFileName
	os.popen(cmd).read()
	return compiledFileName;

def closure(fileName,output="."):
	closureFileName = output + "\\" +  os.path.basename(fileName.replace(".js",".closure.js"))
	content = open(fileName,"r").read()
	content = '(function(){' + content + '})();'
	closureFile = open(closureFileName ,"w")
	closureFile.write(content)
	print "closure... " + closureFileName
	closureFile.close()
	return closureFileName

def document(fileName,output="docs",jsdoc="tools\\jsdoc"):
	cmd = "java -jar " + jsdoc + "\\jsrun.jar " + jsdoc + "\\app\\run.js -a"
	cmd += " -t=" + jsdoc + "\\templates\\jsdoc"
	cmd += " -d=" + output
	cmd += " " + fileName
	print "create documents..."
	os.popen(cmd)
	return output
	



